#!/bin/sh

# desc tomcat重启
# 1.找出所有 tomcat 的进程ID 和 安装目录
# 2.挨个 kill 后重新启动即可

# env
export CATALINA_OPTS="-Djava.security.egd=file:/dev/./urandom"

PID=
CPU=
SERVICE_NAME=$1
DEFAULT_APP_DIR=/data/service
TMP_PATH=/tmp/$SERVICE_NAME.tmp
START_CMD='java -jar'

# 1
ps aux | grep -v grep | grep ${SERVICE_NAME}.jar | awk '{printf("%s %s\n", $2, $3)}' > $TMP_PATH

## 2
echo "Service Pid Infos:$TMP_PATH"
cat $TMP_PATH

# start or restart
if [[ ! -s $TMP_PATH ]]
then
    $START_CMD $DEFAULT_APP_DIR/$SERVICE_NAME.jar 1>/dev/null 2>&1 &
    sleep 3

    # ps service
    echo "check ${SERVICE_NAME} running........"
    ps aux|grep ${SERVICE_NAME}.jar
    echo "${SERVICE_NAME} 重启完毕"
    sleep 2
else
# for loop
while read line
do
    # echo "line:" $line
    PID=`echo $line | awk '{print $1}'`
    CPU=`echo $line | awk '{print $2}'`
    echo "PID:$PID CPU:$CPU ${DEFAULT_APP_DIR}:${SERVICE_NAME}.jar"

    # gc 信息打印
    echo "show gc info:jstat -gc $PID 1000 5"
    jstat -gc $PID 1000 5

    # kill and startup service
    echo "kill and startup service........"
    kill -9 $PID
    $START_CMD $DEFAULT_APP_DIR/$SERVICE_NAME.jar 1>/dev/null 2>&1 &
    sleep 3

    # ps service
    echo "check ${SERVICE_NAME} running........"
    ps aux|grep ${SERVICE_NAME}.jar
    echo "${SERVICE_NAME} 重启完毕"
    sleep 2
done < $TMP_PATH
fi